package JAVAFXManyWindow.init;

import JAVAFXManyWindow.impl.GetPostDat;
import JAVAFXManyWindow.impl.infodata;
import JAVAFXManyWindow.pojo.MainMe;
import com.alibaba.fastjson.JSONObject;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.coobird.thumbnailator.Thumbnails;
import sun.font.FontDesignMetrics;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 这个TCP的websocketService服务
 * 核心代码编写
 * @author 10125
 */
public class JXBrowserServerTcp extends TcpDat {

    private final static String sendString = new String("HTTP/1.1 200 OK \r\n Server: Microsoft-IIS/4.0 \r\n Access-Control-Allow-Origin:* \r\n ");
    private final static Map<String, String> sts = new HashMap<>();
    public static JFileChooser img=new JFileChooser();
    public static JFileChooser exe=new JFileChooser();
    public static List<String> html = new ArrayList<>();
    public static List<String> javascriptpath = new ArrayList<>();
    public static List<String> cssstylepath = new ArrayList<>();
    public static String IPAddtress="";
    private static BASE64Encoder base64en = new BASE64Encoder();
    private static BASE64Decoder base64de = new BASE64Decoder();
    static {
        FileNameExtensionFilter filterimg= new FileNameExtensionFilter("可选图片文件","jpg","bmp","gif","pcx","jpeg","tif","png","raw","tga","svg","jpg");
        img.setFileFilter(filterimg);
        FileNameExtensionFilter filterexe= new FileNameExtensionFilter("可选执行文件","exe");

    }
    private String getImageToBase64(String imgFile) {
        // 读取图片字节数组
        try {
            InputStream in = (InputStream) this.getClass().getClassLoader().getResourceAsStream(imgFile);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(readStream(in));// 返回Base64编码过的字节数组字符串
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String readFile(String file) throws Exception {
        try {
            synchronized (TcpDat.class) {
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(file);
                return readInputStream(inputStream);
            }
        } catch (Exception e) {
            System.err.println("文件找不到读写失败了");
        }
        return "";
    }

    private String readInputStream(InputStream inputStream) throws IOException {
        try {
            synchronized (TcpDat.class) {
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 5 * 1024 * 1024);
                String str = "";
                int item = bufferedInputStream.read();
                if (item == -1) {
                    return null;
                } else {
                    str = str + "" + (char) item;
                    int len = bufferedInputStream.available();
                    if (len > 0) {
                        byte[] dats = new byte[len];
                        bufferedInputStream.read(dats);
                        str = str + new String(dats, "UTF-8");
                    }
                    inputStream.close();
                    bufferedInputStream.close();
                    return new String(str.getBytes("UTF-8"), "UTF-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public String setscanUHttp(int prot){
        String ip =MacAddressIP4();
        if(ip.equals("")==false){
            return "http://"+MacAddressIP4()+":"+prot+"/";
        }else {
            return "http://"+"127.0.0.1"+":"+prot+"/";
        }

    }

    public byte[] readStream(InputStream inStream) throws Exception {
        try {
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream(5 * 1024 * 1024);
            byte[] buffer = new byte[inStream.available()];
            int len = -1;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
                outSteam.flush();
            }
            inStream.close();
            outSteam.close();
            return outSteam.toByteArray();
        } catch (Exception e) {
        }
        return null;
    }

    public static String byteArrToBinStr(byte[] b) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            result.append(Long.toString(b[i] & 0xff, 2) + "");
        }
        return result.toString().substring(0, result.length() - 1);
    }

    private byte[] readimages(String fs) {
        try {
            synchronized (TcpDat.class) {
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fs);
                return readStream(inputStream);
            }
        } catch (Exception e) {
            System.err.println("文件找不到读写失败了");
        }
        return null;
    }

    public int initcssjs(List<String> htm, List<String> js, List<String> css) {
        try {
            synchronized (TcpDat.class) {
                sts.clear();
                html.clear();
                javascriptpath.clear();
                cssstylepath.clear();
                html=htm;
                javascriptpath=js;
                cssstylepath=css;
                if (html != null) {
                    for (String htmls : html) {
                        sts.put(htmls, readFile(htmls));
                    }
                }
                if (javascriptpath != null) {
                    for (String dajs : javascriptpath) {
                        sts.put(dajs, sendString + "Content-Type: text/javascript;Charset=UTF-8 \r\n\r\n" + readFile(dajs));
                    }
                }
                if (cssstylepath != null) {
                    for (String dacs : cssstylepath) {
                        sts.put(dacs, sendString + "Content-Type: text/css;Charset=UTF-8 \r\n\r\n" + readFile(dacs));
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sts.size();
    }
    public Long Prm(String presssname){
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("cmd /c tasklist"); // cmd /c calc
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
            String line = null;
            while ((line = input.readLine()) != null) {
                String gt =textcenent(line.replace(" ",""),presssname,"K");
                String[] as = gt.split("Console\\d{1}|Services\\d{1}");
                if(as.length==2){
                   return Long.valueOf(Arrays.asList(as).get(1).replace(",",""))/1024;
                }
            }
        }catch (Exception e){e.printStackTrace();System.exit(0);}
        return 0l;
    }
    public List<String> MacAddress(){
        List<String> list = new ArrayList<>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("cmd /c ipconfig /all"); // cmd /c calc
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
            String line = null;
            while ((line = input.readLine()) != null) {
                Pattern r = Pattern.compile("物理地址. . . . . . . . . . . . . : ([A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2}");
                // 现在创建 matcher 对象
                Matcher matcher = r.matcher(line);
                while (matcher.find()){
                    list.add(matcher.group().split(" : ")[1]);
                }
            }
            return list;
        }catch (Exception e){e.printStackTrace();System.exit(0);}
        return list;
    }

    private String MacAddressIP(){
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("cmd /c ipconfig"); // cmd /c calc
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
            String line = null;
            while ((line = input.readLine()) != null) {
                Pattern r = Pattern.compile("默认网关. . . . . . . . . . . . . : \\d+\\.\\d+\\.\\d+");
                // 现在创建 matcher 对象
                Matcher matcher = r.matcher(line);
                while (matcher.find()){
                    return matcher.group().split(" : ")[1];
                }
            }
            return "";
        }catch (Exception e){e.printStackTrace();System.exit(0);}
        return "";
    }
    public String MacAddressIP4(){
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("cmd /c ipconfig"); // cmd /c calc
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
            String line = null;
            while ((line = input.readLine()) != null) {
                Pattern r = Pattern.compile("IPv4 地址 . . . . . . . . . . . . : \\d+\\.\\d+\\.\\d+\\.\\d+");
                // 现在创建 matcher 对象
                Matcher matcher = r.matcher(line);
                while (matcher.find()){
                    int dat = matcher.group().split(" : ")[1].indexOf(MacAddressIP());
                    if(dat>-1){
                        return  matcher.group().split(" : ")[1];
                    }
                }
            }
            return "";
        }catch (Exception e){e.printStackTrace();System.exit(0);}
        return "";
    }

    public String textcenent(String alltext, String index_x, String index_z) {
        int index_head = alltext.indexOf(index_x, 0);
        if (index_head > 0) {
            index_head += index_x.length();
        }
        int index_end = alltext.indexOf(index_z, index_head);
        if (index_head < 0 || index_end < 0) {
            return "";
        }
        String Addr = alltext.substring(index_head, index_end);
        return Addr;
    }

    public void GetJXBrowserServerTcp(String httpServerAddress,int port, String backgroundcolor, GetPostDat getPostDat) {
        try{
            Socket client = new Socket(httpServerAddress, port);
            client.close();
            MainMe.jxBrowserServerTcp.AddressURL("http://"+httpServerAddress+":"+port+"/index.html");
            System.exit(0);
        }catch(Exception e){
            IPAddtress=MainMe.jxBrowserServerTcp.setscanUHttp(port);
            serverTcp(httpServerAddress, port, new infodata() {
                @Override
                public void dat(String messages, InputStream inputStream, OutputStream outputStream) {
                    try {
                        synchronized (TcpDat.class) {
                            if (messages.length() > 0) {
                                String Httppath = textcenent(messages, "/", "HTTP").trim();
                                if (Httppath.equals("") == false) {
                                    if (Httppath.length() > 0) {
                                        if (Pattern.matches("(.*)\\.(html)", Httppath) == true) {
                                            getPostDat.addressUrl(Httppath);
                                        }
                                        if (Httppath.indexOf(".html?") > -1) {
                                            String[] Gets = Httppath.split(".html\\?");
                                            if (Gets.length > 0 && Gets.equals("Accept-Language: zh-CN,zh;q=0.9") == false) {
                                                List<String> as = Arrays.asList(Gets[1].split("&"));
                                                getPostDat.dat(as, Httppath, outputStream);
                                                StringBuilder datsa = new StringBuilder();
                                                datsa.append(sendString);
                                                datsa.append("Content-Type: text/html;image/png;Charset=UTF-8 \r\n\r\n");
                                                datsa.append("<!DOCTYPE html><html lang='en'><head><meta name='renderer' content='webkit'><link rel='shortcut icon' href='/favicon.ico' type='image/x-icon'><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><meta charset='UTF-8'><title>JAVAFXManyWindow</title><meta name='viewport' content='width=device-width, initial-scale=1.0' > <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no' >");
                                                if (javascriptpath != null) {
                                                    for (String dajs : javascriptpath) {
                                                        datsa.append("<script rel='script' rev='script' type='text/javascript' src='" + dajs + "'></script>");
                                                    }
                                                }
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("index.min.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("respond.min.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("html5.min.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("javascriptUI.js") + "</script>");
                                                datsa.append("<script rel='script' type='text/javascript'>function maxleftright() {document.getElementsByTagName('body')[0].style.width  = (document.body.scrollWidth)+'px';document.getElementsByTagName('body')[0].style.height = (document.body.scrollHeight)+'px';}</script>");
                                                if (cssstylepath != null) {
                                                    for (String dacs : cssstylepath) {
                                                        datsa.append("<link rev='stylesheet' media='all' rel='stylesheet' type='text/css' href='" + dacs + "' />");
                                                    }
                                                }
                                                datsa.append("<style rel='stylesheet' type='text/css'>body{background-color:" + backgroundcolor + ";margin: 0px auto 0px auto;}</style>");
                                                datsa.append("</head><body id="+IPAddtress+" oncontextmenu='return false' ondragstart='return false'  oncut='return false;' style='float: left;width: 100%;height: 100%;' >");
                                                if (as.get(0).split("=")[0].equals("LOAD")==true) {
                                                    datsa.append(sts.get(as.get(0).split("=")[1]));
                                                }else if (as.get(0).split("=")[0].equals("FILE")==true) {
                                                    do{
                                                        if(MainMe.isopen==0){
                                                            MainMe.isopen=1;
                                                            String bas ="";
                                                            if(as.get(1).split("=")[1].equals("null")==false){
                                                                bas = getImageToBase64FileSwing(as.get(1).split("=")[1]);
                                                            }else {
                                                                bas = getImageToBase64FileSwing("null");
                                                            }
                                                            if(bas.equals("null")==false && MainMe.ImgDat.size()<=Integer.valueOf(as.get(0).split("=")[1])){
                                                                AjaxGetResponse(outputStream,bas);
                                                            }else{
                                                                MainMe.ImgDat.clear();
                                                                IMGITEM imgitem = new IMGITEM();
                                                                AjaxGetResponse(outputStream,"null");
                                                                datsa.append(sts.get(Httppath.split("\\?")[0]));
                                                            }
                                                        }
                                                    }while (MainMe.isopen==1);
                                                }else if(as.get(0).split("=")[0].equals("RUNTIME") ==true){
                                                    Runtime.getRuntime().exec(URLDecoder.decode(as.get(0).split("=")[1],"UTF-8"));
                                                    datsa.append(sts.get(as.get(0).split("=")[1]));
                                                }else if(as.get(0).split("=")[0].equals("RUNAPPLICTION") ==true){
                                                    do{
                                                        if(MainMe.isfile==0){
                                                            MainMe.isfile=1;
                                                            String bas = getFilePathSwing();
                                                            if(bas.equals("null")==false){
                                                                Runtime.getRuntime().exec(bas);
                                                                datsa.append(sts.get(as.get(0).split("=")[1]));
                                                            }else{
                                                                datsa.append(sts.get(Httppath.split("\\?")[0]));
                                                            }
                                                        }
                                                    }while (MainMe.isfile==1);
                                                }else if(as.get(0).split("=")[0].equals("END")==true){
                                                    System.exit(0);
                                                } else {
                                                    datsa.append(sts.get(Httppath.split("\\?")[0]));
                                                }
                                                datsa.append("</body></html>");
                                                outputStream.write(datsa.toString().getBytes("utf-8"));
                                                outputStream.flush();
                                                outputStream.close();
                                            }
                                        }
                                        String[] Posta = messages.split("\n");
                                        if (Posta.length > 0) {
                                            List<String> vas = new ArrayList<>();
                                            vas.clear();
                                            for (String val : Posta) {
                                                if (val.equals("") != true) {
                                                    vas.add(val);
                                                }
                                            }
                                            if (vas.get(vas.size() - 1).indexOf("=") > -1 && vas.get(vas.size() - 1).equals("Accept-Language: zh-CN,zh;q=0.9") == false) {
                                                List<String> as = Arrays.asList(vas.get(vas.size() - 1).split("&"));
                                                getPostDat.dat(as, Httppath, outputStream);
                                                vas.clear();
                                            }
                                        }
                                        for (String htm : html) {
                                            if (Httppath.equals(htm) == true && Pattern.matches("(.*)\\.(html)", Httppath) == true) {
                                                StringBuilder datsa = new StringBuilder();
                                                datsa.append(sendString);
                                                datsa.append("Content-Type: text/html;image/png;Charset=UTF-8 \r\n\r\n");
                                                datsa.append("<!DOCTYPE html><html lang='en'><head><meta name='renderer' content='webkit'><link rel='shortcut icon' href='/favicon.ico' type='image/x-icon'><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><meta charset='UTF-8'><title>JAVAFXManyWindow</title><meta name='viewport' content='width=device-width, initial-scale=1.0'><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no' >");
                                                if (javascriptpath != null) {
                                                    for (String dajs : javascriptpath) {
                                                        datsa.append("<script rel='script' rev='script' type='text/javascript' src='" + dajs + "'></script>");
                                                    }
                                                }
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("index.min.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("respond.min.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("html5.min.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>" + readFile("javascriptUI.js") + "</script>");
                                                datsa.append("<script rev='script' rel='script' type='text/javascript'>function maxleftright() {document.getElementsByTagName('body')[0].style.width  = (document.body.scrollWidth)+'px';document.getElementsByTagName('body')[0].style.height = (document.body.scrollHeight)+'px';}</script>");
                                                if (cssstylepath != null) {
                                                    for (String dacs : cssstylepath) {
                                                        datsa.append("<link rev='stylesheet' rel='stylesheet' type='text/css' href='" + dacs + "' />");
                                                    }
                                                }
                                                datsa.append("<style rel='stylesheet' type='text/css'>body{background-color:" + backgroundcolor + ";margin: 0px auto 0px auto;}</style>");
                                                datsa.append("</head><body id="+IPAddtress+" oncontextmenu='return false' ondragstart='return false'  oncut='return false;' style='float: left;width: 100%;height: 100%;' >");
                                                datsa.append(sts.get(Httppath));
                                                datsa.append("</body></html>");
                                                outputStream.write(datsa.toString().getBytes("utf-8"));
                                                outputStream.flush();
                                                outputStream.close();
                                                break;
                                            }
                                        }
                                        for (String cstyle : cssstylepath) {
                                            if (Httppath.equals(cstyle) == true || Pattern.matches("(.*)\\.(css|css.*)", Httppath) == true) {
                                                outputStream.write(sts.get(Httppath.substring(0,Httppath.indexOf("?")>-1?Httppath.indexOf("?"):Httppath.length())).getBytes("UTF-8"));
                                                outputStream.flush();
                                                outputStream.close();
                                                break;
                                            }
                                        }
                                        for (String js : javascriptpath) {
                                            if (Httppath.equals(js) == true || Pattern.matches("(.*)\\.(js|js.*)", Httppath) == true) {
                                                outputStream.write(sts.get(Httppath.substring(0,Httppath.indexOf("?")>-1?Httppath.indexOf("?"):Httppath.length())).getBytes("UTF-8"));
                                                outputStream.flush();
                                                outputStream.close();
                                                break;
                                            }
                                        }
                                        if (Pattern.matches("(.*)\\.(woff2|woff|ttf|woff2.*|woff.*|ttf.*)", Httppath) == true) {
                                            String dire = sendString + "Content-Type: application/font-woff;charset=utf-8 \r\n\r\n" + readFile(Httppath.substring(0,Httppath.indexOf("?")>-1?Httppath.indexOf("?"):Httppath.length()));
                                            outputStream.write(dire.getBytes("UTF-8"));
                                            outputStream.flush();
                                            outputStream.close();
                                        } else if (Pattern.matches("(.*)\\.(txt|txt.*)", Httppath) == true) {
                                            String dire = sendString + "Content-Type: text/plain;charset=utf-8 \r\n\r\n" + readFile(Httppath.substring(0,Httppath.indexOf("?")>-1?Httppath.indexOf("?"):Httppath.length()));
                                            outputStream.write(dire.getBytes("UTF-8"));
                                            outputStream.flush();
                                            outputStream.close();
                                        } else if (Pattern.matches("(.*)\\.(jpg|bmp|gif|pcx|jpeg|tif|png|raw|tga|svg|jpg.*|bmp.*|gif.*|pcx.*|jpeg.*|tif.*|png.*|raw.*|tga.*|svg.*)", Httppath) == true) {
                                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                                            BufferedImage buffImg = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream(Httppath.substring(0,Httppath.indexOf("?")>-1?Httppath.indexOf("?"):Httppath.length())));
                                            ImageIO.write(buffImg, "png", out);
                                            byte[] bs = out.toByteArray();
                                            String dire = "HTTP/1.1 200 OK (CRLF)\r\naccept-ranges:bytes\r\nCharset=UTF-8\r\nContent-Type:image/png\r\nContent-length:" + bs.length + "\r\n\r\n";
                                            outputStream.write(dire.getBytes("UTF-8"));
                                            outputStream.write(bs);
                                            outputStream.flush();
                                            outputStream.close();
                                        } else if (Pattern.matches("(.*)\\.(ico|ico.*)", Httppath) == true) {
                                            String img = getImageToBase64(Httppath.substring(0,Httppath.indexOf("?")>-1?Httppath.indexOf("?"):Httppath.length()));
                                            String dire = "HTTP/1.1 200 OK\r\nAccept-Ranges: bytes;\r\nContent-Type:image/x-icon;\r\nContent-length:" + img.length() + "\r\n\r\n";
                                            outputStream.write(dire.getBytes("UTF-8"));
                                            outputStream.write(img.getBytes("UTF-8"));
                                            outputStream.flush();
                                            outputStream.close();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) { }
                }
            });
        }
    }

    public void AddressURL(String url) {
        if (java.awt.Desktop.isDesktopSupported()) {
            try {
                // 创建一个URI实例
                java.net.URI uri = java.net.URI.create(url);
                // 获取当前系统桌面扩展
                java.awt.Desktop dp = java.awt.Desktop.getDesktop();
                // 判断系统桌面是否支持要执行的功能
                if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
                    // 获取系统默认浏览器打开链接
                    dp.browse(uri);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void AjaxGetResponse(OutputStream outputStream, String s) {
        try {
            String statusline = "HTTP/1.1 200 OK\r\n";
            byte[] statusline_to_bytes = statusline.getBytes("UTF-8");
            byte[] content_to_bytes = s.getBytes("UTF-8");
            String header = "\"Access-Control-Allow-Origin:*\r\nContent-Type:text/html;application/x-www-form-urlencoded\r\ncharset=UTF-8\r\n";
            byte[] header_to_bytes = header.getBytes("UTF-8");
            outputStream.write(statusline_to_bytes);
            outputStream.write(header_to_bytes);
            outputStream.write(new byte[]{(byte) '\r', (byte) '\n'});
            outputStream.write(content_to_bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {

        }
    }
    public String getImageToBase64FileSwing(String ispng){
        try {
            synchronized (JXBrowserServerTcp.class){
                if(img.isVisible()==true){
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    int value =img.showDialog(new JLabel(), "选择");
                    if(value==JFileChooser.FILES_ONLY){
                        File file=img.getSelectedFile();
                        if(file.isFile()){
                            InputStream in = new FileInputStream(file.getPath());
                            BASE64Encoder encoder = new BASE64Encoder();
                            MainMe.isopen=0;
                            IMGITEM imgitem  = new IMGITEM();
                            imgitem.setNAME(file.getName());
                            if(ispng.equals("null")==true){
                                imgitem.setPATH("data:image/"+file.getPath().substring(file.getPath().length()-3,file.getPath().length())+";base64,"+encoder.encode(MainMe.jxBrowserServerTcp.readStream(in)));
                            }else{
                                imgitem.setPATH("data:image/"+file.getPath().substring(file.getPath().length()-3,file.getPath().length())+";base64,"+addWatermark(encoder.encode(MainMe.jxBrowserServerTcp.readStream(in)),ispng));
                            }
                            MainMe.ImgDat.add(imgitem);
                            return JSONObject.toJSONString(MainMe.ImgDat);
                        }
                    }else{
                        MainMe.isopen=0;
                        MainMe.ImgDat.clear();
                    }
                }

            }
        }catch (Exception e){
            MainMe.isopen=0;
            MainMe.ImgDat.clear();
            return "null";

        };
        MainMe.ImgDat.clear();
        return "null";
    }

    public String getFilePathSwing(){
        try {
            synchronized (JXBrowserServerTcp.class){
                if(exe.isVisible()==true){
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    int value =exe.showDialog(new JLabel(), "选择");
                    if(value==JFileChooser.FILES_ONLY){
                        File file=exe.getSelectedFile();
                        if(file.isFile()){
                            InputStream in = new FileInputStream(file.getPath());
                            BASE64Encoder encoder = new BASE64Encoder();
                            MainMe.isfile=0;
                            return file.getPath();
                        }
                    }else{
                        MainMe.isfile=0;
                    }
                }

            }
        }catch (Exception e){ MainMe.isfile=0;return "null";}
        MainMe.isfile=0;
        return "null";
    }
    public static String GetImagesBase64(String url, String encoding) {


        StringBuffer buffer=new StringBuffer();
        InputStreamReader isr=null;

        try {
            // 建立网络连接
            URL urlObj = new URL(url);
            // 打开网络连接
            URLConnection uc = urlObj.openConnection();
            /*
             * io 流
             * 从服务器下载源码到本地
             * */
            isr =new InputStreamReader(uc.getInputStream(),"UTF-8");//建立文件的输入流
            BufferedReader reader =new BufferedReader(isr);//缓冲

            String line=null;
            while ((line=reader.readLine())!=null) {

                buffer.append(line+"\n");

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{

            try{
                if(null!=isr)isr.close();}
            catch(IOException e){
                e.printStackTrace();
            }
        }
        return buffer.toString();

    }
    public String addWatermark(String srcStr,String content) throws IOException,Exception{
        //根据传递的base64图片的大小来决定水印图片的大小。
        //处理透明信息
        float alpha =0.2F;
        int srcWidth = 0;
        int srcHeight = 0;
        byte[] b ;
        try {
            b = base64de.decodeBuffer(srcStr);
            InputStream is = new java.io.ByteArrayInputStream(b);
            BufferedImage src = ImageIO.read(is);
            if(src != null ){
                srcWidth = src.getWidth(null);
                srcHeight = src.getHeight(null);
                if(srcWidth<=0||srcHeight<=0){
                    return null;
                }
                //根据原始图片变换水印图片的尺寸
                /*添加水印*/
                BufferedImage img = new java.awt.image.BufferedImage(srcWidth, srcHeight,BufferedImage.TYPE_USHORT_565_RGB);
                //创建画板
                Graphics2D graph = img.createGraphics();
                graph.drawImage(src.getScaledInstance(srcWidth,srcHeight,Image.SCALE_SMOOTH), 0, 0, null);
                //把原图印到图板上
//                graph.drawImage(src,null,0,0);
                //设置透明度,alpha
                graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
                Font font = new Font("微软雅黑", Font.BOLD, 48);
                FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
                graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                graph.setFont(font);
                graph.setColor(Color.WHITE);
                int textWidth = metrics.stringWidth(content);
                int widthX = (srcWidth - textWidth) / 2;
                int height = (srcHeight/2);
                graph.drawString(content, widthX, height);//图片上写文字
                /*把图片转换为字节*/

                ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
                Thumbnails.of(img).scale(1.0f).outputQuality(1f).outputFormat("png").toOutputStream(jpegOutputStream);
//                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
//                encoder.encode(img);
                byte[] resultByte = jpegOutputStream.toByteArray();
                graph.dispose();
                System.out.println(base64en.encode(resultByte));
                return base64en.encode(resultByte);
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public String getURLAddress(){
        String path =  System.getProperty("java.class.path");
        Pattern pattern = Pattern.compile("(?<=\\\\)[^\\\\]+(?=\\\\)");
        Matcher matcher = pattern.matcher(path);
        String str="";
        while(matcher.find()){
            str = path.substring(0,matcher.end(0))+"/";
        }
       return str.replaceAll("\\\\","/");
    }
    public String DatTime(Long tims,String val){
        try {
            URL url = new URL("https://m.tianqi.com/");
//        <font face="geneva," arial,="" helvetica,="" sans-seif="" size="5" color="#000000">2018年8月12日</font>
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            httpURLConnection.addRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            httpURLConnection.addRequestProperty("Connection", "keep-alive");
            httpURLConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.addRequestProperty("User-Agent", "mozilla/5.0 (linux; u; android 4.1.2; zh-cn; mi-one plus build/jzo54k) applewebkit/534.30 (khtml, like gecko) version/4.0 mobile safari/534.30 micromessenger/5.0.1.352");
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufr = new BufferedReader(isr);
            StringBuffer stringBuffer = new StringBuffer();
            String str;
            while ((str = bufr.readLine()) != null) {
                stringBuffer.append(str);
            }
            String tis = textcenent(stringBuffer.toString(),"<div class=\"date\">","</div>").replace("年","-").replace("月","-").replace("日","");
            Pattern pattern =Pattern.compile("([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))");
            Matcher matcher = pattern.matcher(tis);
            String as ="";
            while(matcher.find()){
                as = tis.substring(0,matcher.end(0));
            }
            if(as.equals("")==false){
                if(Long.parseLong(MainMe.jxBrowserServerTcp.dateToStamp(as))<tims){
                    return "go";
                }else {
                    Messagess(val);
                    System.exit(0);
                }
            }
        }catch (Exception e){
            if(Long.parseLong(localhsotDate())<tims){
                return "go";
            }else {
                Messagess(val);
                System.exit(0);
            }
        }
        return "";
    }
    public String dateToStamp(String time){
        try {
            String stap;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(time);
            long ts = date.getTime();//获取时间的时间戳
            stap = String.valueOf(ts);
            return stap;
        }catch (Exception e){return "";}
    }
    public String localhsotDate(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return dateToStamp(df.format(new Date()));
    }
    public void Messagess(String val){
        JOptionPane.showMessageDialog(null, val);
    }

}


